import { defineStore } from 'pinia'
// import { getAccessToken, setToken, removeToken } from '@/utils/auth'
import { getInfo, logout, login } from '@/api/login/index'
import { getDept } from '@/api/system/dept'
import { showToastAsync, toast } from '@/utils/toast'
import { getAccessToken, getRefreshToken, getExpiresTime, setToken, removeToken } from '@/utils/auth'

interface UserVO {
	id: number
	avatar: string
	nickname: string
	deptId: number
	deptName: string
}

interface UserInfoVO {
	// USER 缓存
	permissions: string[]
	roles: string[]
	isSetUser: boolean
	user: UserVO
}
import config from '@/config'
const baseUrl = config.baseUrl + config.baseApi;
export const useUserStore = defineStore('admin-user', {
	state: (): UserInfoVO => ({
		permissions: [],
		roles: [],
		isSetUser: false,
		user: {
			id: 0,
			avatar: '',
			nickname: '',
			deptId: 0,
			deptName: '',
		}
	}),
	getters: {
		getPermissions(): string[] {
			return this.permissions
		},
		getRoles(): string[] {
			return this.roles
		},
		getIsSetUser(): boolean {
			return this.isSetUser
		},
		getUser(): UserVO {
			return this.user
		}
	},
	actions: {
		// 登录
		async Login(userInfo: any) {
			const username = userInfo.username.trim()
			const password = userInfo.password
			const captchaVerification = userInfo.captchaVerification
			const refreshToken = getRefreshToken()
			try {


				const res = await login(username, password, captchaVerification)
				setToken({
					accessToken: res.accessToken,
					refreshToken: res.refreshToken,
					expiresTime: res.expiresTime
				})

				return res
			} catch (error) {
				throw new Error('网络请求失败')
			}
			// return new Promise((resolve, reject) => {
			// 	login(username, password, captchaVerification).then(res => {
			// 		res = res.data;
			// 		// 设置 token
			// 		setToken(res)
			// 		resolve()
			// 	}).catch(error => {
			// 		reject(error)
			// 	})
			// })
		},

		async setUserInfoAction() {
			if (!getAccessToken()) {
				this.resetState()
				return null
			}
			let userInfo = uni.getStorageSync('user')
			if (!userInfo) {
				userInfo = await getInfo()
			}
			this.permissions = userInfo.permissions
			this.roles = userInfo.roles
			this.user = userInfo.user
			// 获取部门名称
			if (this.user.deptId) {
				try {
					const deptInfo = await getDept(this.user.deptId)
					if (deptInfo) {
						this.user.deptName = deptInfo.name
						userInfo.user.deptName = deptInfo.name
					}
				} catch (error) {
					console.error('获取部门信息失败:', error)
				}
			}
			this.isSetUser = true
			uni.setStorageSync('user', userInfo)
			uni.setStorageSync('roleRouters', userInfo.menus)
		},
		async setUserAvatarAction(avatar: string) {
			const userInfo = uni.getStorageSync('user')
			// NOTE: 是否需要像`setUserInfoAction`一样判断`userInfo != null`
			this.user.avatar = avatar
			userInfo.user.avatar = avatar
			uni.setStorageSync('user', userInfo)
		},
		async setUserNicknameAction(nickname: string) {
			const userInfo = uni.getStorageSync('user')
			// NOTE: 是否需要像`setUserInfoAction`一样判断`userInfo != null`
			this.user.nickname = nickname
			userInfo.user.nickname = nickname
			uni.setStorageSync('user', userInfo)
		},
		async logout() {
			await logout()
			removeToken()
			uni.removeStorageSync('user')
			uni.removeStorageSync('roleRouters') // 删除用户缓存
			this.resetState()
		},
		resetState() {
			this.permissions = []
			this.roles = []
			this.isSetUser = false
			this.user = {
				id: 0,
				avatar: '',
				nickname: '',
				deptName: '',
				deptId: 0
			}
		},

	},

	// 添加持久化配置
	persist: {
		key: 'admin-user-storage', // 指定一个存储的key
		storage: {
			getItem(key) {
				return uni.getStorageSync(key)
			},
			setItem(key, value) {
				return uni.setStorageSync(key, value)
			}
		}
	}
})